package com.tsmti.tags.form.support;

import com.tsmti.core.util.ObjectUtils;
import com.tsmti.core.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.jsp.PageContext;

/**
 * @Package：com.tsmti.tags.form.support
 * @Class：FreemarkerFormTagHelper
 * @Description： TODO
 * @Author：
 * @Date：Created in 2018/3/14 17:15
 * @Company:
 * @Version：
 * @Modified By:
 */
public class FreemarkerFormTagHelper {
	protected Map<String, Object> staticAttributes = new HashMap<String, Object>();

	public static FreemarkerFormTagHelper getFormHelper() {
		return new FreemarkerFormTagHelper();
	}

	public static Map<String, Object> getTagStatic(Object tag, PageContext pageContext) {
		return new FreemarkerFormTagHelper().initFreeMarkerMap(tag, pageContext);
	}

	public Map<String, Object> initFreeMarkerMap(Object tag, PageContext pageContext) {
		Map<String, Object> rootMap = new HashMap<String, Object>(16);
		String ctx = pageContext.getServletContext().getContextPath();
		String staticPath = pageContext.getServletContext().getContextPath() + "/statics";
		rootMap.put("ctx", ctx);
		rootMap.put("staticPath", staticPath);
		initStaticAttribute(tag);
		rootMap.putAll(staticAttributes);
		return rootMap;
	}

	public void initStaticAttribute(Object tag) {
		// 获取实体类的所有属性，返回Field数组
		Field[] field = tag.getClass().getDeclaredFields();
		// 遍历所有属性
		for (int j = 0; j < field.length; j++) {
			Field field2 = field[j];
			if (ObjectUtils.isBaseDataType(field2.getType())) {
				// 获取属性的名字
				String name = field[j].getName();
				setStaticAttribute(name, ReflectionUtils.invokeGetter(tag, name));
			}
		}
	}

	/**
	 * 设置静态属性
	 */
	public void setStaticAttribute(String localName, Object value) {
		if (this.staticAttributes == null) {
			this.staticAttributes = new HashMap<String, Object>(16);
		}
		if (!ObjectUtils.isNullOrEmpty(value)) {
			staticAttributes.put(localName, value);
		}
	}
}
